package com.luck.of.wise.somenslider;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.luck.of.wise.somenslider.util.BluetoothService;
import com.luck.of.wise.somenslider.util.Constants;
import com.luck.of.wise.somenslider.util.Log;
import com.luck.of.wise.somenslider.util.SPHandler;
import com.luck.of.wise.somenslider.widget.SomenView;
import com.luck.of.wise.somenslider.widget.SomenView.OnSomenListener;

public class SomenSliderActivity extends Activity {
    static int REQUEST_ENABLE_BLUETOOTH = 101;
    // Debugging
    private static final String TAG = "SomenSliderActivity";

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_AS_SERVER_CHANGE = 1;
    public static final int MESSAGE_STATE_AS_CLIENT_CHANGE = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_READ = 4;
    public static final int MESSAGE_DEVICE_NAME = 5;
    public static final int MESSAGE_TOAST = 6;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_ENABLE_BT = 3;
    private static final int REQUEST_PICK_BLUETOOTH_DEVICE = 4;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothService mService = null;
    String mConnectedDeviceName;
    private static final int MENU_SETTING = 0;

    ImageView mZaruImageView;
    ImageView mTake1ImageView;
    ImageView mTake2ImageView;
    SomenView mSomenView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.somen_slider_activity);
        // 画面が暗くならないようにする
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // BluetoothAdapter取得
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.equals(null)) {
            Toast.makeText(this, R.string.bluetooth_not_support, Toast.LENGTH_SHORT).show();
            finish();
        }

        SPHandler sp = SPHandler.getInstance(this);
        if (sp.showMessage()) {
            new AlertDialog.Builder(this).setTitle(R.string.first).setMessage(R.string.first_message)
                    .setPositiveButton("OK", null).show();
            sp.setShowMessage(false);
        }

        mTake1ImageView = (ImageView) findViewById(R.id.take1);
        mTake2ImageView = (ImageView) findViewById(R.id.take2);
        mZaruImageView = (ImageView) findViewById(R.id.zaru);
        mSomenView = (SomenView) findViewById(R.id.somen);
        mSomenView.setOnSomenListener(new OnSomenListener() {
            @Override
            public void onFlowNext(String type) {
                if (mService != null) {
                    mService.writeAsServer(type.getBytes());
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "++ ON START ++");

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (mService == null) {
                mService = new BluetoothService(this, mHandler);
                mService.start();
                Intent i = getIntent();
                if (i.hasExtra(Constants.EXTRA_SERVER)) {
                    int serverFlag = i.getIntExtra(Constants.EXTRA_SERVER, 0);
                    i.removeExtra(Constants.EXTRA_SERVER);
                    if (serverFlag == 1) {
                    } else {
                        pickBluetooth();
                    }
                }
            }
        }
    }

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_AS_SERVER_CHANGE:
                if (mService != null && mService.getStateAsServer() == BluetoothService.STATE_NONE) {
                    mService.startAcceptAsServer();
                }
                setLayout();
                break;
            case MESSAGE_STATE_AS_CLIENT_CHANGE:
                Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                setLayout();
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                Log.d(TAG, readMessage);
                if (mSomenView != null) {
                    mSomenView.flowSomen(readMessage.substring(0, 1));
                }
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Context c = getApplicationContext();
                Toast.makeText(c, c.getString(R.string.connected, mConnectedDeviceName), Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                break;
            }
        }

        private void setLayout() {
        	if (mService == null) {
        		return;
        	}
            if (!mService.isLast()) {
                if (mTake1ImageView != null) {
                    mTake1ImageView.setVisibility(View.VISIBLE);
                }
                if (mTake2ImageView != null) {
                    mTake2ImageView.setVisibility(View.GONE);
                }
                if (mZaruImageView != null) {
                    mZaruImageView.setVisibility(View.GONE);
                }
            } else {
                if (mTake1ImageView != null) {
                    mTake1ImageView.setVisibility(View.GONE);
                }
                if (mTake2ImageView != null) {
                    mTake2ImageView.setVisibility(View.VISIBLE);
                }
                if (mZaruImageView != null) {
                    mZaruImageView.setVisibility(View.VISIBLE);
                }
            }
            try {
                Button buttonClient = (Button) findViewById(R.id.buttonClient);
                if (mService.getStateAsClient() == BluetoothService.STATE_CONNECTED) {
                    buttonClient.setVisibility(View.GONE);
                } else {
                    buttonClient.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                mService = new BluetoothService(this, mHandler);
                mService.start();
            } else {
                // User did not enable Bluetooth or an error occurred
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bluetooth_not_enabled, Toast.LENGTH_SHORT).show();
                finish();
            }
            break;
        case REQUEST_PICK_BLUETOOTH_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, R.string.connecting, Toast.LENGTH_SHORT).show();
                connectDevice(data.getExtras().getString("address"));
            }
        }
    }

    private void connectDevice(String address) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        mService.connectAsClient(device);
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.buttonClient:
            pickBluetooth();
            break;
        }
    }

    private void pickBluetooth() {
        Intent intent = new Intent(this, BluetoothListPickerActivity.class);
        this.startActivityForResult(intent, REQUEST_PICK_BLUETOOTH_DEVICE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("SomenSliderActivity#onPause", "Start.");

        stopBackgroundAnimation();

        Log.i("SomenSliderActivity#onPause", "End.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("SomenSliderActivity#onResume", "Start.");

        startBackgroundAnimation();

        Log.i("SomenSliderActivity#onResume", "End.");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("SomenSliderActivity#onStop", "Start.");

        if (mService != null) {
            mService.stop();
            mService = null;
        }

        Log.i("SomenSliderActivity#onStop", "End.");
    }

    private void startBackgroundAnimation() {
        Log.i("SomenSliderActivity#startBackgroundAnimation", "Start.");

        Animation anim = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.water_anim);
        ImageView view = (ImageView) this.findViewById(R.id.water);
        view.setAnimation(anim);

        Log.i("SomenSliderActivity#startBackgroundAnimation", "End.");
    }

    private void stopBackgroundAnimation() {
        Log.i("SomenSliderActivity#stopAnimation", "Start.");

        ImageView view = (ImageView) this.findViewById(R.id.water);
        view.clearAnimation();

        Log.i("SomenSliderActivity#stopAnimation", "End.");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_SETTING, Menu.NONE, R.string.bluetooth_settings).setIcon(
                android.R.drawable.ic_menu_preferences);
        return result;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        boolean result = super.onMenuItemSelected(featureId, item);

        switch (item.getItemId()) {
        case MENU_SETTING:
            Intent intent = new Intent("android.settings.SETTINGS");
            intent.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
            startActivity(intent);
            break;
        }
        return result;
    }
}